<template>
  <div class="box">
    <div class="search">
      <SearchForm :formInputs="state.formInputs" @submit="search" />
    </div>
    <div class="table">
      <p :style="{ textAlign: 'right', marginBottom: '5px' }">
        <a-button @click="action('add')" type="primary" link
          ><template #icon>
            <PlusOutlined />
          </template>
          添加</a-button
        >
      </p>
      <a-table
        size="middle"
        :data-source="state.tableData"
        :columns="[
          {
            title: '船舶名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
          },
          {
            title: '船舶类型',
            dataIndex: 'type',
            key: 'type',
            ellipsis: true,
          },
          {
            title: '工程编号',
            dataIndex: 'code',
            key: 'code',
            ellipsis: true,
          },
          {
            title: '总管',
            key: 'manager',
            dataIndex: 'manager',
            ellipsis: true,
          },
          {
            title: '总管电话',
            key: 'managerTel',
            dataIndex: 'managerTel',
            ellipsis: true,
          },
          {
            title: '施工工序',
            key: 'workFlows',
            dataIndex: 'workFlows',
            width: 500,
          },
          {
            title: '进厂时间',
            key: 'enterTime',
            dataIndex: 'enterTime',
            ellipsis: true,
          },
          {
            title: '进坞时间',
            key: 'startTime',
            dataIndex: 'startTime',
            ellipsis: true,
          },
          {
            title: '出坞时间',
            key: 'endTime',
            dataIndex: 'endTime',
            ellipsis: true,
          },
          {
            title: '出厂时间',
            key: 'outTime',
            dataIndex: 'outTime',
            ellipsis: true,
          },
          {
            title: '状态',
            key: 'complete',
            dataIndex: 'complete',
            ellipsis: true,
            width: 80,
            align: 'center',
          },
          {
            title: '操作',
            key: 'action',
            width: 180,
            align: 'center',
          },
        ]"
        :pagination="state.pager"
        @change="handleTableChange"
        stripe
        bordered
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.key === 'action'">
            <a-space
              :size="10"
              spacer="|"
              v-if="!specialIds.includes(record.shipId) && !record.complete"
            >
              <DeleteBtn
                title="确认删除?"
                label="删除"
                @onDelete="action('remove', record)"
              />
              <a-button type="link" @click="action('edit', record)" link
                ><template #icon>
                  <EditOutlined />
                </template>
                编辑</a-button
              >
            </a-space>
          </template>
          <template v-else-if="column.key === 'shipName'"
            >{{ record.ship.name }}
          </template>
          <template v-else-if="column.key === 'shipType'"
            >{{ record.ship.type }}
          </template>
          <template v-else-if="column.key === 'enterTime'"
            >{{ dayjs(record.enterTime).format("YYYY-MM-DD") }}
          </template>
          <template v-else-if="column.key === 'startTime'"
            >{{
              record.startTime
                ? dayjs(record.startTime).format("YYYY-MM-DD")
                : null
            }}
          </template>
          <template v-else-if="column.key === 'endTime'"
            >{{
              record.endTime ? dayjs(record.endTime).format("YYYY-MM-DD") : null
            }}
          </template>
          <template v-else-if="column.key === 'outTime'"
            >{{
              record.outTime ? dayjs(record.outTime).format("YYYY-MM-DD") : null
            }}
          </template>
          <template v-else-if="column.key === 'workFlows'">
            <template v-if="record.workFlows">
              <a-tag
                v-for="o in _.split(record.workFlows, ',')"
                color="green"
                >{{ o }}</a-tag
              ></template
            >
          </template>
          <template v-else-if="column.key === 'complete'">
            <a-tag :color="!!text ? '#87d068' : '#f50'">{{
              !!text ? "已竣工" : "未竣工"
            }}</a-tag>
          </template>
        </template>
      </a-table>
    </div>
    <FormModal
      :formConfig="state.formConfig"
      @submit="submit"
      ref="dialogRef"
    />
  </div>
</template>

<script setup>
import { onBeforeMount, getCurrentInstance, reactive, ref } from "vue";
import _ from "lodash";
import FormModal from "@/components/FormModal.vue";
import SearchForm from "@/components/SearchForm.vue";
import DeleteBtn from "@/components/DeleteBtn.vue";
import dayjs from "dayjs";
import { works } from "@/utils/shipflow/works.js";

// 对于工序递归转换
const transWork = (list) => {
  return _.map(list, (o) => {
    const obj = { label: o.label, value: o.label, key: o.label };
    if (o.children) {
      obj.checkable = false;
      obj.children = transWork(o.children);
    }
    return obj;
  });
};

const { proxy } = getCurrentInstance();
const state = reactive({
  formInputs: [
    { label: "进厂时间范围", type: "dateRange", name: "dateRange" },
    { label: "船舶", type: "select", name: "shipId", options: [] },
    {
      label: "状态",
      type: "select",
      name: "complete",
      options: [
        { label: "不限", value: null },
        { label: "已竣工", value: 1 },
        { label: "未竣工", value: 0 },
      ],
    },
  ],
  formConfig: {
    title: "维修登记信息提交",
    items: [
      {
        type: "hidden",
        name: "id",
      },
      {
        label: "工程编号",
        type: "input",
        name: "code",
        span: 12,
        rules: [
          {
            required: true,
            message: "请输入工程编号",
          },
        ],
      },
      {
        label: "船舶",
        type: "select",
        name: "shipId",
        span: 12,
        rules: [
          {
            required: true,
            message: "请选择船舶",
          },
        ],
        options: [],
      },
      {
        label: "总管",
        type: "input",
        name: "manager",
        span: 12,
        rules: [
          {
            max: 50,
            message: "不能超过50字符",
          },
        ],
      },
      {
        label: "总管电话",
        type: "input",
        name: "managerTel",
        span: 12,
        rules: [
          {
            pattern: /^1[3|4|5|7|8|9]\d{9}$/,
            message: "请输入正确的手机号",
          },
        ],
      },
      {
        label: "施工工序",
        type: "treeSelect",
        name: "workFlows",
        options: transWork(works),
        multiple: true,
        rules: [
          {
            required: true,
            message: "请选择施工工序",
          },
        ],
      },
      {
        label: "进厂时间",
        type: "date",
        name: "enterTime",
        span: 12,
        rules: [
          {
            required: true,
            message: "请输入进厂时间",
          },
        ],
      },
      {
        label: "出厂时间",
        type: "date",
        name: "outTime",
        span: 12,
        rules: [
          {
            required: true,
            message: "请输入进厂时间",
          },
        ],
      },
      {
        label: "进坞时间",
        type: "date",
        name: "startTime",
        span: 12,
      },
      {
        label: "出坞时间",
        type: "date",
        name: "endTime",
        span: 12,
      },
    ],
  },
  searchObj: { dateRange: [], shipId: null, complete: null },
  tableData: [],
  pager: {
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: false,
    size: "normal",
  },
});
const dialogRef = ref();

const specialIds = [10000001, 10000002, 10000003, 10000004];

const getList = (page) => {
  const { dateRange, shipId, complete } = state.searchObj;
  let startTime,
    endTime = null;
  if (dateRange && dateRange.length === 2) {
    startTime = dateRange[0]?.format("YYYY-MM-DD 00:00:00");
    endTime = dateRange[1]?.format("YYYY-MM-DD 23:59:59");
  }
  proxy.$axios
    .get("/ship_repair/list", {
      params: {
        pageNumber: page,
        pageSize: state.pager.pageSize,
        startTime,
        endTime,
        shipId,
        complete,
      },
    })
    .then(({ success, data }) => {
      if (success) {
        const list = data.content;
        state.tableData = list;
        state.pager.total = data.totalCount;
        state.pager.current = page;
      }
    });
};

const handleTableChange = ({ current }) => {
  getList(current);
};

const search = (value) => {
  state.searchObj.dateRange = value.dateRange;
  state.searchObj.shipId = value.shipId;
  state.searchObj.complete = value.complete;
  getList(1);
};

const submit = (values) => {
  let method = "post";
  let url = "/ship_repair";
  if (values.id) {
    method = "put";
    url += `/${values.id}`;
  }
  proxy.$axios({ method, data: values, url }).then(({ success, msg }) => {
    if (success) {
      dialogRef.value.cancel();
      proxy.$message.success("提交成功");
      getList(1);
    }
  });
};

const action = (type, record) => {
  if (type === "add") {
    dialogRef.value.handleOpenForm({});
  } else if (type === "edit") {
    if (record.workFlows && typeof record.workFlows === "string") {
      record.workFlows = record.workFlows.split(",");
    }
    dialogRef.value.handleOpenForm({ ...record });
  } else if (type === "remove") {
    proxy.$axios.delete(`/ship_repair/${record.id}`).then(({ success }) => {
      if (success) {
        getList(1);
      }
    });
  }
};

//生命周期钩子函数
onBeforeMount(() => {
  proxy.$axios.get("/ship/dict").then(({ success, data }) => {
    if (success) {
      const one = _.find(state.formInputs, { name: "shipId" });
      one.options = [{ label: "不限", value: null }, ...data];

      const the = _.find(state.formConfig.items, { name: "shipId" });
      // 特殊的船舶不允许添加船舶施工信息
      the.options = _.filter(data, (o) => !specialIds.includes(o.value));
    }
  });

  getList(1);
});
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;

  .search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
  }

  .table {
    flex: 1;
    padding: 2px;
    overflow-y: auto;
  }
}
</style>
